﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.Cache.Memory
{
    public class ShanYuMemoryCache : BaseCache
    {
        private MemoryCache _memoryCache;

        public ShanYuMemoryCache(string name)
            : base(name)
        {
            _memoryCache = new MemoryCache(name);
        }

        public override void Clear()
        {
            _memoryCache.Dispose();
            _memoryCache = new MemoryCache(Name);
        }

        public override object GetOrDefault(string key)
        {
            return _memoryCache.Get(key);
        }

        public override void Remove(string key)
        {
            _memoryCache.Remove(key);
        }

        public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
        {
            if (value is null)
            {
                throw new Exception($"Can't insert null to the cache! The key is {key}");
            }

            var policy = new CacheItemPolicy();

            if (absoluteExpireTime != null && absoluteExpireTime.HasValue)
            {
                policy.AbsoluteExpiration = DateTimeOffset.Now.Add(absoluteExpireTime.Value);
            }
            else if (slidingExpireTime != null && slidingExpireTime.HasValue)
            {
                policy.SlidingExpiration = slidingExpireTime.Value;
            }
            else if (AbsoluteExpireTime != null && AbsoluteExpireTime.HasValue)
            {
                policy.AbsoluteExpiration = DateTimeOffset.Now.Add(AbsoluteExpireTime.Value);
            }
            else
            {
                policy.SlidingExpiration = SlidingExpireTime;
            }
            if (ChangeMonitors.Any())
            {
                foreach (var item in ChangeMonitors)
                    policy.ChangeMonitors.Add(item);
            }

            _memoryCache.Set(key, value, policy);
        }
    }
}
